import './style.css'
import 'remixicon/fonts/remixicon.css'
import './tailwind.config'
import { createApp } from 'petite-vue'
import jsonbin from './jsonbin.es'
import { getJson } from './utils'

const { log, dir, table, clear, warn, error } = console

main()
async function main() {
  const config = await getJson('./config.json')
  let bin
  createApp({
    bin: null,
    binId: null,
    chats: [],
    selectedRole: null,
    currentChat: '',
    ipAddress: '--',
    ticker: null,
    showIP: config.showIP,
    roles: config.roles,
    interval: config.interval,
    handleKeyDown(e) {
      const { code, isComposing, shiftKey } = e
      if (code === 'Enter') {
        if (!isComposing && !shiftKey) { 
          e.preventDefault()
          this.send()
        }
      }
    },
    ref(name, el) {
      this[name] = el
    },
    scrollToBottom() {
      setTimeout(()=>{
        this.listEl.scrollTop = this.listEl.scrollHeight
      },0)
    },
    getBinId(param='id') {
      // return '678a16c0acd3cb34a8ccfbb5'
      const url = new URL(window.location.href);
      return url.searchParams.get(param);
    },
    async send() {
      if (this.currentChat === '') return
      const currentChat = this.currentChat.replace(/\n/g, '<br>').replace(/ /g, '&nbsp;')
      this.chats.push({role:this.selectedRole, content:currentChat, ip:this.ipAddress})
      this.currentChat = ''
      this.scrollToBottom()
      this.update()
    },
    share() {
      const text = this.getLink()
      navigator.clipboard.writeText(text)
      .then(() => {
        this.chats.push({role:'FastChat', content:`<span class="text-green-500">分享链接已复制到剪贴板</span>`, ip:''})
        console.log(`URL copied.`, text)
      })
      .catch(err => { console.error('Failed to copy text.', err) })
    },
    getLink() {
      return window.location.origin + window.location.pathname + '?id=' + this.binId
    },
    async burn() {
      this.chats = [{role:'FastChat', content:`<span class="text-green-500">https://gitee.com/wavef/fast-chat</span>`, ip:''}]
      this.update()
    },
    async update() {
      clearInterval(this.ticker)
      await bin.update(this.chats)
      this.refresh()
    },
    async read() {
      const res = await bin.read()
      return res.record
    },
    async refresh() {
      this.read()
      this.ticker = setInterval(async ()=>{
        const res = await this.read()
        if (this.chats.length < res.length) {
          this.chats = res
        }
        this.scrollToBottom()
        log(this.chats[this.chats.length-1])
      }, Math.max(this.interval, 5000))
    },
    async mounted() {
      bin = new jsonbin(this.getBinId())
      this.binId = bin.id
      this.chats = await this.read()
      this.selectedRole = this.roles[0]
      this.ipAddress = await this.getUserIP()
      this.refresh()
      this.scrollToBottom()
    },
    async getUserIP() {
      const req = await fetch('https://api.ipify.org?format=json')
      const res = await req.json()
      return res.ip
    }
  }).mount()
}